package Utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 创建数据库连接池工具类
 */
public class DruidJDBCUtils {
   private static Connection conn=null;
    private static DataSource ds=null;
    static {
        try {
            Properties pro=new Properties();
            pro.load(DruidJDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
             ds= DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得连接对象
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /**
     * 获得连接池对象
     * @return
     */
    public static DataSource getDataSource(){
        return ds;
    }
    public static void close(PreparedStatement sate, Connection conn){
        if (sate!=null){
            try {
                sate.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /**
     * 释放资源
     * @param res
     * @param sate
     * @param conn
     */
    public static void close(ResultSet res, PreparedStatement sate, Connection conn){
        if (res!=null){
            try {
                res.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (sate!=null){
            try {
                sate.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}
